<!-- <!doctype html> -->
<html lang="en">

<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        video {
            border: 1px solid #ccc;
            display: block;
            margin: 0 0 20px 0;
            float: left;
        }

        canvas {
            margin-top: 20px;
            border: 1px solid #ccc;
            display: block;
        }
    </style>
</head>

<body>
        {% csrf_token %}
    <p>
        <button onclick="openMedia()">打开摄像头</button>
        <button onclick="closeMedia()">关闭摄像头</button>
        <button class="recorderControl" onclick="recording()">开始录制</button>
        <button id="preview_button" onclick="" disabled="disabled">预览</button>
        <button id="upload_button" onclick="" disabled="disabled">上传并判断</button>
    </p>
       <video id="video" class="bg"></video>
       <canvas id="qr-canvas"></canvas>
</body>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    var video = document.querySelector('video');
    var text = document.getElementById('text');
    var upload_button = document.getElementById('upload_button')
    var preview_button = document.getElementById('preview_button')
    var canvas1 = document.getElementById('qr-canvas');
    var context1 = canvas1.getContext('2d');
    var mediaStreamTrack;
   
    // 一堆兼容代码
    window.URL = (window.URL || window.webkitURL || window.mozURL || window.msURL);
    if (navigator.mediaDevices === undefined) {
    navigator.mediaDevices = {};
    }
    if (navigator.mediaDevices.getUserMedia === undefined) {
    navigator.mediaDevices.getUserMedia = function(constraints) {
     var getUserMedia = navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia;
     if (!getUserMedia) {
     return Promise.reject(new Error('getUserMedia is not implemented in this browser'));
     }
     return new Promise(function(resolve, reject) {
     getUserMedia.call(navigator, constraints, resolve, reject);
     });
    }
    } 
   
    //摄像头调用配置
    var mediaOpts = {
    audio: false,
    video: true,
    video: { facingMode: "environment"}, // 或者 "user"
    video: { width: 768, height: 768 }
    // video: { facingMode: { exact: "environment" } }// 或者 "user"
    }


    // 回调
    function successFunc(stream) {
    mediaStreamTrack = stream;
    video = document.querySelector('video');
    if ("srcObject" in video) {
     video.srcObject = stream
    } else {
     video.src = window.URL && window.URL.createObjectURL(stream) || stream
    }
    video.play();
    }

    function errorFunc(err) {
    alert(err.name);
    }



    function recodingVideo(stream){
        var videorecorder = new MediaRecorder(stream);
        var recorderControl=document.querySelector(".recorderControl"); 
        
        // 调用屏幕显示
        successFunc(stream);
        
        // 建立回调函数，点击录制按钮后的相应
        var buffers=[];
        recorderControl.onclick=function(){
        // this.textContent=="录制"?video.play():video.pause();
        this.textContent=="开始录制"?videorecorder.start():videorecorder.stop();
        this.textContent=this.textContent=="开始录制"?"停止":"开始录制";
        };

        //TODO:需要改为当点击上传时，上传文件
        videorecorder.ondataavailable=function(event){
            console.log("aaa")
            buffers=event.data;
            var file = new File([buffers], 'video.mkv');
            var formdata = new FormData();
            var csrf_data = $('[name=csrfmiddlewaretoken]').val();
            formdata.append("file_obj", file);
            formdata.append('csrfmiddlewaretoken',csrf_data);
            var upload_button = document.getElementById('upload_button');
            var preview_button = document.getElementById('preview_button');
            upload_button.disabled = false;
            preview_button.disabled = false;
            upload_button.onclick = function(){
                $.ajax(
                {
                    // url填写django对应的路由
                    url:'{% url "video_recoding" %}',
                    type:'post',
                    data:formdata,
                    processData: false,
                    contentType: false,
                }
                )
            };
            preview_button.onclick = function(){
                video = document.querySelector('video');
                // src_url = buffers;
                // console.log(buffers);
                url = window.URL.createObjectURL(buffers);
                console.log(url);
                if ("srcObject" in video) {
                    video.srcObject = url;
                } else {
                    video.src = window.URL && window.URL.createObjectURL(buffers) || buffers;
                }
                    video.play();
                }

            }
        }

    // 正式启动摄像头
    function openMedia(){
    navigator.mediaDevices.getUserMedia(mediaOpts).then(recodingVideo);
    // .catch(errorFunc);
    }
   
    //关闭摄像头
    function closeMedia(){
    mediaStreamTrack.getVideoTracks().forEach(function (track) {
     track.stop();
     context1.clearRect(0, 0,context1.width, context1.height);//清除画布
    });
    }
   </script>
</html>